package com.bidevalution.business.impl;

import com.bidevalution.business.service.BeBidResultService;
import com.bidevalution.business.service.BeRemoteExpertLoginService;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.dao.entity.BeSectionParameter;
import com.bidevalution.dao.entity.ExpertWarnMsgVo;
import com.bidevalution.dao.mapper.BeBidResultMapper;
import com.bidevalution.dao.mapper.BeSectionInfoMapper;
import com.bidevalution.dao.mapper.BeSectionParameterMapper;
import com.bidevalution.service.BidResultService;
import com.bidevalution.support.context.Constants;
import com.qtp.core.model.Response;
import com.qtp.core.util.GsonUtil;
import com.qtp.core.util.Md5Util;
import com.qtp.core.util.OConvertUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 中标结果页面相关接口实现类
 * Created by glodon on 2019-11-19.
 */
@Log4j2
@Service
public class BeBidResultServiceImpl implements BeBidResultService {
    @Autowired
    private BeBidResultMapper beBidResultMapper;
    @Autowired
    private BeSectionParameterMapper parameterMapper;
    @Autowired
    BeRemoteExpertLoginService beRemoteExpertLoginService;
    @Autowired
    private BidResultService bidResultService;
    @Autowired(required = false)
    private BeSectionInfoMapper beSectionInfoMapper;

    /**
     * 查询项目信息
     * @param sectionId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> getProjectInfo(String sectionId) throws Exception {
        return beBidResultMapper.getProjectInfo(sectionId);
    }

    /**更新项目信息
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public void updateProjectInfo(Map<String, Object> map) throws Exception {
        beBidResultMapper.updateProjectInfo(map);
    }

    /**
     * 获取中标单位信息
     * @param sectionId
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> getBidInfoList(String sectionId) throws Exception {
        //获取候选人数量
        Integer candidateNum = getCandidateNum(sectionId);
        return beBidResultMapper.getBidInfoList(sectionId,candidateNum);
    }
    /**
     * 获取中标单位业绩信息
     * @param enterpriseId
     * @param performanceType 业绩类型 0，资格，1 评分
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> getBidPerformanceList(String enterpriseId, String performanceType) throws Exception {
        return beBidResultMapper.getBidPerformanceList(enterpriseId, performanceType);
    }

    /**更新投标单位信息
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public void updateBidInfoList(List<Map<String, Object>> map) throws Exception {
        beBidResultMapper.updateBidInfoList(map);
    }


    /**
     * 更新中标单位业绩信息
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public void updateBidPerformanceList(List<Map<String, Object>> map) throws Exception {
        beBidResultMapper.updateBidPerformanceList(map);
    }

    @Override
    public Response saveBidPerformanceList(List<Map<String, Object>> map) {
        try{
            Map<String, String> tmpMap = new HashMap<>(8);
            for (Map item : map) {
                String sectionId = OConvertUtils.getString(item.get("sectionId"));
                if (OConvertUtils.isEmpty(item.get("seqId")) && OConvertUtils.isEmpty(item.get("sectionId")) && OConvertUtils.isEmpty(item.get("enterpriseId"))) {
                    return Response.fail("参数不完整");
                }
                String projectId = tmpMap.get(Md5Util.getMD5(sectionId));
                if(OConvertUtils.isEmpty(projectId)){
                    projectId = OConvertUtils.getString(item.get("sectionId"));
                    BeSectionInfo sectionInfo = beSectionInfoMapper.getSectionInfoById(OConvertUtils.getString(item.get("sectionId")));
                    if (sectionInfo != null && OConvertUtils.isNotEmpty(sectionInfo.getTdProjectid())) {
                        projectId = sectionInfo.getTdProjectid();
                    }
                    tmpMap.put(Md5Util.getMD5(sectionId), projectId);
                }
                item.put("projectId", projectId);
            }
            beBidResultMapper.saveBidPerformanceList(map);
            return Response.ok();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Response.fail("保存中标单位业绩失败");
        }
    }

    @Override
    public Response isProjPerf(String sectionId){
        if (StringUtils.isBlank(sectionId)) {
            Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
        }
        try {
            BeSectionInfo sectionInfo = beSectionInfoMapper.getSectionInfoById(sectionId);
            if (sectionInfo != null && OConvertUtils.isNotEmpty(sectionInfo.getTdProjectid())) {
                String projectId = sectionInfo.getTdProjectid();
                Map<String, Object> map = beBidResultMapper.getAuditPara(projectId, "ProjPerf");
                if(map != null){
                    return Response.ok(OConvertUtils.getInt(map.get("aupa_ParaValue"),0));
                }
            }
            return Response.ok(0);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Response.fail("查询数据失败");
        }
    }

    /**
     * 查询否决投标单位的原因及依据
     * @param sectionId
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> getUnpassedEnterpriseList(String sectionId) throws Exception {
        return beBidResultMapper.getUnpassedEnterpriseList(sectionId);
    }

    /**
     * 查询评标专家公示
     * @param sectionId
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> getSectionExpertList(String sectionId) throws Exception {
        return beBidResultMapper.getSectionExpertList(sectionId);
    }

    /**
     * 查询专家评分情况
     * @param sectionId
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> getExpertScoreList(String sectionId) throws Exception {
        List<Map<String, Object>> list = beBidResultMapper.getExpertScoreList(sectionId);
        if (list != null && list.size() > 0) {
            for (Map<String, Object> map : list) {
                if(map!= null) {
                    String expertNames = OConvertUtils.getString(map.get("expertNames"));
                    String scores = OConvertUtils.getString(map.get("scores"));
                    String[] expertNameArr = expertNames.split(",");
                    String[] scoreArr = scores.split(",");
                    for(int i=0; i< expertNameArr.length; i++) {
                        map.put(expertNameArr[i],scoreArr[i]);
                    }
                    map.remove("expertNames");
                    map.remove("scores");
                }
            }
        }
        return list;
    }


    /**
     * 中标结果推送
     * @param sectionId
     * @return
     * @throws Exception
     */
    @Override
    public Response<String> pushBidResult(String sectionId) throws Exception {
        //获取候选人数量
        Integer candidateNum = getCandidateNum(sectionId);
        //查询项目信息
        Map<String, Object> segmentEvaluationRecord = beBidResultMapper.getSegmentEvaluationRecord(sectionId);
        //查询专家个人意见List
        List<Map<String, Object>> evaluationRecordList = beBidResultMapper.getEvaluationRecord(sectionId,candidateNum);
        //中标人业绩List
        List<Map<String, Object>> WinBidPerformanceList = beBidResultMapper.getWinBidPerformance(sectionId,candidateNum);
        //废标单位列表List
        List<Map<String, Object>> invalidBidRecordList = beBidResultMapper.getInvalidBidRecord(sectionId);
        //专家评分情况List
        List<Map<String, Object>> expertScoreRecordList = beBidResultMapper.getExpertScoreRecord(sectionId);
        //单位得分表List
        List<Map<String, Object>> winBidScoreList = beBidResultMapper.getWinBidScore(sectionId);
        //中标单位信息List
        List<Map<String, Object>> winBidInfoList = beBidResultMapper.getWinBidInfo(sectionId, candidateNum);

        Response<String> response = bidResultService.pushBidResult(segmentEvaluationRecord,evaluationRecordList,WinBidPerformanceList,
                invalidBidRecordList,expertScoreRecordList,winBidScoreList,winBidInfoList);
        if(!response.isSuccess()) {
            return response;
        } else {
            BeSectionInfo beSectionInfo = beSectionInfoMapper.selectByPrimaryKey(sectionId);
            //中标结果推送状态为否
            if (Constants.ZERO.equals(beSectionInfo.getIsResultPush())) {
                //如果是远程异地评标则需要推送评标结束状态
                if(Constants.ONE.equals(beSectionInfo.getIsRemote())) {
                    beRemoteExpertLoginService.updateEvalutionState(beSectionInfo.getSectionCode());
                }
                beSectionInfo.setIsResultPush(Constants.ONE);
                //更新推送完成状态
                beSectionInfoMapper.updateByPrimaryKeySelective(beSectionInfo);
            }
            return Response.ok();
        }
    }

    @Override
    public boolean insertPerformance(Map<String, Object> params) throws Exception {
        String performanceId = null;
        int requestType = OConvertUtils.getInt(params.get("requestType"));
        if (requestType == 1){
            performanceId = OConvertUtils.getString(params.get("appe_AppeID"));
        }
        Map<String,Object> map = beBidResultMapper.getPerformanceParams(OConvertUtils.getString(params.get("enterprise_id")),performanceId);
        if (map != null && !map.isEmpty()){
            String projectId = OConvertUtils.getString(map.get("appe_ProjectID"));
            if (OConvertUtils.isNotEmpty(projectId)){
                params.put("appe_ProjectID",projectId);
            }else {
                return false;
            }
            if (requestType == 1 && OConvertUtils.isEmpty(OConvertUtils.getString(map.get("appe_Idx")))){
                return false;
            }
            int idx = OConvertUtils.getInt(map.get("appe_Idx"));
            params.put("appe_Idx",++idx);
            beBidResultMapper.insertPerformance(params);
            return true;
        }else {
            return false;
        }
    }

    @Override
    @Transactional
    public void delPerformances(String performanceIds) throws Exception {
        log.info("LOG[]delPerformances[]{},params={}", "删除业绩", GsonUtil.toJsonWithGson(performanceIds));
        try {
            String[] ids = performanceIds.split(",");
            for (int i = 0; i < ids.length; i++) {
                if (beBidResultMapper.delPerformances(ids[i]) != 1){
                    throw new RuntimeException("业绩id不存在performanceId=" + ids[i]);
                }
            }
        }catch (Exception e){
            log.error("LOG[]delPerformances[]{},error={},params={}","删除业绩异常",GsonUtil.toJsonWithGson(e),GsonUtil.toJsonWithGson(performanceIds));
            throw e;
        }
    }

    @Override
    public String getPerformanceFilePath(String sectionEnterpriseId,String atfiAnnexType) {
        log.info("LOG[]getPerformanceFilePath[]{},params={}", "获取业绩文件路径",GsonUtil.toJsonWithGson(sectionEnterpriseId));
        try {
            return beBidResultMapper.getPerformanceFilePath(sectionEnterpriseId,atfiAnnexType);
        }catch (Exception e){
            log.error("LOG[]getPerformanceFilePath[]{},error={},params={}","获取业绩文件路径异常",GsonUtil.toJsonWithGson(e),GsonUtil.toJsonWithGson(sectionEnterpriseId));
        }
        return null;
    }

    @Override
    public List<ExpertWarnMsgVo> getRankErrorInfo(String sectionStepId) {
        log.info("LOG[]getRankErrorInfo[]{},params={}", "获取排名异常信息",GsonUtil.toJsonWithGson(sectionStepId));
        try {
            return beBidResultMapper.getRankErrorInfo(sectionStepId);
        }catch (Exception e){
            log.error("LOG[]getRankErrorInfo[]{},error={},params={}","获取排名异常信息异常",GsonUtil.toJsonWithGson(e),GsonUtil.toJsonWithGson(sectionStepId));
            return new ArrayList<>();
        }
    }

    @Override
    public Integer getStandardUnitNum(String sectionStepId, String columnName) {
        return beBidResultMapper.getStandardUnitNum(sectionStepId, columnName);
    }

    @Override
    public Integer getStandardUnitNumByBusiness(String sectionStepId) {
        return beBidResultMapper.getStandardUnitNumByBusiness(sectionStepId);
    }


    /**
     * 获取中标候选人数量
     * @param sectionId
     * @return
     * @throws Exception
     */
    private Integer getCandidateNum(String sectionId) throws Exception {
        String[] str= {"AdvanceNum"};
        List<BeSectionParameter> beSectionParameterList = parameterMapper.queryListByParamIds(sectionId, str);
        Integer limit=3;
        if(beSectionParameterList != null && beSectionParameterList.size()>0 && beSectionParameterList.get(0) != null) {
            limit = OConvertUtils.getInt(beSectionParameterList.get(0).getParamValue(),3);
        }
        return limit;
    }
}
